package com.flea.service.search;

import com.flea.model.Product;
import com.flea.model.ProductDoc;
import com.flea.repository.es.ProductDocRepository;
import com.flea.repository.jdbc.ProductRepository;
import com.flea.service.ISearchService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class FullTextSearch implements ISearchService {

    @Resource
    private ProductDocRepository productDocRepository;

    @Resource
    private ProductRepository productRepository;

    @Override
    public Page<Product> searchProducts(String key, Pageable pageable) {
        // 从ES中根据关键字查询
        Page<ProductDoc> productDocPage = productDocRepository.findByNameOrDesc(key, key, pageable);

        // 根据从ES查询出来的ID,再去数据库中批量查询出整个数据
        List<Integer> productIdList = productDocPage.stream().map(ProductDoc::getProductId).collect(Collectors.toList());
        Map<Integer, Product> productMap = new HashMap<>();
        productRepository.findAllById(productIdList).forEach(e -> {
            productMap.put(e.getId(), e);
        });

        // 把ProductDocPage转化成ProductPage  Page<ProductDoc> -> Page<Product>
        return productDocPage.map(e -> productMap.get(e.getProductId()));
    }
}
